﻿using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using XCI.Core;
using XCI.Extensions;
using XCI.Helper;
using XCI.Sys.Helper;
using XCI.Sys.Model;

namespace XCI.Sys.Forms
{
    public partial class FrmRibbonMain : RibbonForm,IMainForm
    {
        private MainFormManager mainFormManager;
        public FrmRibbonMain()
        {
            InitializeComponent();
            if (WinFormHelper.IsDesignMode()) WinFormHelper.InitDesignFont();
            SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.Selectable | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.SupportsTransparentBackColor, true);
        }

        protected override void OnLoad(EventArgs e)
        {
            if (WinFormHelper.IsDesignMode()) WinFormHelper.InitDesignFont();
            base.OnLoad(e);
        }

        private void InitForm()
        {
            mainFormManager = new MainFormManager(this, tabbedView1,true);
            SysApp.MainFormManager = mainFormManager;
            mainFormManager.InitActiveUser();
            mainFormManager.SetStatusInfo(statusTime, statusUser, null, null, statusOs, statusServer);
            BuildMenu();
        }

        private void BuildMenu()
        {
            var modules = SysApp.GetCurrentUserOwnModules().Where(p => p.IsMenu).ToList();
            var firstModules = modules.Where(p => p.ParentId.Equals(TreeOperateHelper.RootTreeNodeId));
            var pages = new List<RibbonPage>();
            foreach (var first in firstModules)
            {
                var page = BuildPage(first);
                var secondModules = modules.Where(p => p.ParentId.Equals(first.Id));
                var groups = new List<RibbonPageGroup>();

                RibbonPageGroup firstGroup = null;
                foreach (var second in secondModules)
                {
                    var threeModules = modules.Where(p => p.ParentId.Equals(second.Id)).ToArray();
                    if (threeModules.Any())
                    {
                        var group = BuildGroup(second);
                        groups.Add(group);

                        AddItems(group, threeModules);
                    }
                    else
                    {
                        if (firstGroup == null)
                        {
                            firstGroup = BuildGroup(first);
                            groups.Add(firstGroup);
                        }

                        AddItems(firstGroup, second);
                    }
                }
                page.Groups.AddRange(groups.ToArray());
                pages.Add(page);
            }
            ribbonControl1.Pages.Clear();
            ribbonControl1.Pages.AddRange(pages.ToArray());
        }

        private void RefreshMenu()
        {
            SysApp.RefreshCurrentUserOwnModules();
            BuildMenu();
        }

        private RibbonPage BuildPage(SysModule module)
        {
            var page = new RibbonPage {Name = module.Code + "_Page", Text = module.Name};
            return page;
        }

        private RibbonPageGroup BuildGroup(SysModule module)
        {
            var group = new RibbonPageGroup
            {
                Name = module.Code + "_Group",
                Text = module.Name,
                ShowCaptionButton = false
            };
            return group;
        }

        private BarButtonItem BuildItem(SysModule module)
        {
            var item = new BarButtonItem {Name = module.Code + "_Item", Caption = module.Name};
            item.ImageOptions.LargeImage = R.DefaultModuleImage32;
            item.Tag = module;
            item.ItemClick += (o, e) =>
            {
                if (e.Item.Tag is SysModule m)
                {
                   mainFormManager.AddDocument(m);
                }
            };
            return item;
        }

        private void AddItems(RibbonPageGroup group, params SysModule[] itemModules)
        {
            var btns = new List<BarItem>();
            foreach (var three in itemModules)
            {
                var btnItem = BuildItem(three);
                btns.Add(btnItem);
            }
            var btnArray = btns.ToArray();
            //ribbonControl1.Items.AddRange(btnArray);
            group.ItemLinks.AddRange(btnArray);
        }

        private void FrmRibbonMain_Load(object sender, EventArgs e)
        {
            InitForm();
        }

        public void SetMessage(string msg)
        {
            statusMsg.Caption = msg;
        }

        private void BtnSetting_ItemClick(object sender, ItemClickEventArgs e)
        {
            //_mainFormManager.SettingMethod();
        }

        private void BtnPassword_ItemClick(object sender, ItemClickEventArgs e)
        {
            mainFormManager.ShowModifyPasswordForm();
        }

        private void BtnLock_ItemClick(object sender, ItemClickEventArgs e)
        {
            mainFormManager.LockUser();
        }

        private void BtnSwitchUser_ItemClick(object sender, ItemClickEventArgs e)
        {
            mainFormManager.SwitchUser();
        }

        private void BtnAbout_ItemClick(object sender, ItemClickEventArgs e)
        {
            mainFormManager.ShowAboutForm();
        }

        private void BtnRefreshMenu_ItemClick(object sender, ItemClickEventArgs e)
        {
            RefreshMenu();
        }

        private void SkinRibbonGalleryBarItem1_GalleryItemClick(object sender, GalleryItemClickEventArgs e)
        {
            SaveTheme(skinName: e.Item.Value.ToStringOrEmpty());
        }

        private void SkinPaletteRibbonGalleryBarItem1_GalleryItemClick(object sender, GalleryItemClickEventArgs e)
        {
            SaveTheme(svgPaletteName: e.Item.Value.ToStringOrEmpty());
        }

        private void SaveTheme(string skinName = null, string svgPaletteName = null)
        {
            var themeSetting = ThemeConfig.Get();
            if (skinName.IsNotEmpty()) themeSetting.Skin = skinName;
            if (svgPaletteName.IsNotEmpty()) themeSetting.SvgPalette = svgPaletteName;
            ThemeConfig.Save();
        }

        public Form OwnForm => this;
        public void AddDocument(FormInfo info)
        {
            mainFormManager.AddDocument(info);
        }

        public void OnMessage(string message)
        {
            statusMsg.Caption = message;
        }
    }
}